<template>
  <view
    class="expandable-text"
    :style="{ maxHeight: isTruncated && !isExpanded ? '176rpx' : textBoxHeight * 2 + 56 + 'rpx' }"
  >
    <view class="text-box fz-14 linh-20" :class="[isTruncated && !isExpanded ? 'ov-3' : '']">
      {{ text }}
    </view>
  </view>
  <view
    class="disFlxAC disFlxJC gap-2 mt-8"
    @click="toggleExpand"
    v-if="isTruncated"
    style="color: #2878ff"
  >
    <text class="fz-14 linh-20">{{ isExpanded ? '收起内容' : '展开内容' }}</text>
    <text class="ali-icon fz-16">{{ isExpanded ? '&#xe67d;' : '&#xe67e;' }}</text>
  </view>
</template>

<script setup lang="ts">
  import { ref, onMounted, watch, getCurrentInstance, computed } from 'vue';
  const props = defineProps<{
    text: string;
  }>();

  const isExpanded = ref(false);

  const isTruncated = computed(() => {
    if (textBoxHeight.value > 60) {
      return true;
    }
    return false;
  });

  const textBoxHeight = ref(0);
  const ins = getCurrentInstance();
  const checkTruncation = () => {
    const query = uni.createSelectorQuery().in(ins!.proxy);
    query
      .select('.text-box')
      .boundingClientRect((res: any) => {
        textBoxHeight.value = res.height;
      })
      .exec();
  };

  const toggleExpand = () => {
    isExpanded.value = !isExpanded.value;
  };

  onMounted(() => {
    checkTruncation();
  });

  watch(
    () => props.text,
    () => {
      console.log(props.text);

      checkTruncation();
    },
    { immediate: true },
  );
</script>

<style lang="scss" scoped>
  .expandable-text {
    overflow: hidden;
    transition: max-height 0.3s ease-in-out;
  }
</style>
